package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.GregorianCalendar;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.filechooser.FileNameExtensionFilter;

import logic.ToGuiFacade;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class pnlMovieAddition extends javax.swing.JPanel {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private JLabel nameLbl;
	private JLabel directorLbl;
	private JLabel lblError;
	private JSpinner spnYear;
	private JButton btnSelectPic;
	private JTextField txtPicture;
	private JLabel jLabel1;
	private JLabel addMovieLbl;
	private JButton cancelBtn;
	private JTextField txtName;
	private JButton btnSubmit;
	private JTextField txtLength;
	private JTextField txtDirector;
	private JTextField txtLang;
	private JTextField txtCategory;
	private JLabel yearLbl;
	private JLabel lengthLbl;
	private JLabel langLbl;
	private JLabel catgoryLab;
//	private String _user;

	public pnlMovieAddition(String user) {
		super();
//		_user = user;
		initGUI();
	}

	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(443, 304));
			this.setLayout(null);
			this.setBackground(new java.awt.Color(255,128,0));
			{
				nameLbl = new JLabel();
				this.add(nameLbl);
				nameLbl.setText("Movie Name:");
				nameLbl.setBounds(23, 62, 98, 17);
			}
			{
				catgoryLab = new JLabel();
				this.add(catgoryLab);
				catgoryLab.setText("Category:");
				catgoryLab.setBounds(23, 94, 98, 14);
			}
			{
				directorLbl = new JLabel();
				this.add(directorLbl);
				directorLbl.setText("Director:");
				directorLbl.setBounds(23, 121, 108, 14);
			}
			{
				langLbl = new JLabel();
				this.add(langLbl);
				langLbl.setText("Language:");
				langLbl.setBounds(23, 148, 114, 14);
			}
			{
				lengthLbl = new JLabel();
				this.add(lengthLbl);
				lengthLbl.setText("Length (Minutes):");
				lengthLbl.setBounds(23, 175, 108, 14);
			}
			{
				yearLbl = new JLabel();
				this.add(yearLbl);
				yearLbl.setText("Year:");
				yearLbl.setBounds(23, 202, 69, 14);
			}
			{
				txtName = new JTextField();
				this.add(txtName);
				txtName.setBounds(161, 60, 260, 21);
			}
			{
				txtCategory = new JTextField();
				this.add(txtCategory);
				txtCategory.setBounds(161, 91, 260, 19);
			}
			{
				txtLang = new JTextField();
				this.add(txtLang);
				txtLang.setBounds(161, 145, 260, 21);
			}
			{
				txtDirector = new JTextField();
				this.add(txtDirector);
				txtDirector.setBounds(161, 118, 260, 21);
			}
			{
				txtLength = new JTextField();
				this.add(txtLength);
				txtLength.setBounds(161, 172, 260, 21);
			}
			{
				btnSubmit = new JButton();
				this.add(btnSubmit);
				btnSubmit.setText("Submit");
				btnSubmit.setBounds(298, 264, 90, 21);
				btnSubmit.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						//System.out.println("submitBtn.actionPerformed, event="+evt);
						try {
							String picture =txtPicture.getText();
							if (validateEnteredData()){
								picture = copyImage(txtPicture.getText(),txtName.getText());
								logic.Facade.getInstance().addMovie(txtName.getText(), txtCategory.getText(), txtDirector.getText(), txtLang.getText(), "0", "0", (String)spnYear.getValue(), txtLength.getText() , picture);
								lblError.setText("movie was added succesfully");
								txtCategory.setText("");
								txtDirector.setText("");
								txtLang.setText("");
								txtLength.setText("");
								txtName.setText("");
								txtPicture.setText("");
								spnYear.setValue("2008");
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
			{
				cancelBtn = new JButton();
				this.add(cancelBtn);
				cancelBtn.setText("back");
				cancelBtn.setBounds(173, 264, 91, 21);
				cancelBtn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						cancelBtnActionPerformed(evt);
					}
				});
			}
			{
				addMovieLbl = new JLabel();
				this.add(addMovieLbl);
				addMovieLbl.setText("Movie Addition");
				addMovieLbl.setBounds(23, 20, 214, 28);
				addMovieLbl.setFont(new java.awt.Font("Arial",1,14));
			}
			{
				jLabel1 = new JLabel();
				this.add(jLabel1);
				jLabel1.setText("Picture:");
				jLabel1.setBounds(23, 229, 108, 14);
			}
			{
				txtPicture = new JTextField();
				this.add(txtPicture);
				txtPicture.setBounds(161, 227, 172, 20);
				txtPicture.setEditable(false);
			}
			{
				btnSelectPic = new JButton();
				this.add(btnSelectPic);
				btnSelectPic.setText("Browse");
				btnSelectPic.setBounds(339, 226, 82, 20);
				btnSelectPic.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						JFileChooser fc = new JFileChooser("c:");
						fc.setAcceptAllFileFilterUsed(false);
						fc.setFileFilter(new FileNameExtensionFilter("Pictures","jpg"));
						fc.setOpaque(true);
						if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
							File fromFile = fc.getSelectedFile();
							txtPicture.setText(fromFile.getAbsolutePath());
						}
					}
				});
			}
			{
				//System.out.println(GregorianCalendar.getInstance().get(GregorianCalendar.YEAR));
				String[] years = new String[GregorianCalendar.getInstance().get(GregorianCalendar.YEAR)-1894];
				for (int i = 1895 ; i <= GregorianCalendar.getInstance().get(GregorianCalendar.YEAR); i++){
					years[i-1895] = ""+(i);
				}
				SpinnerListModel spnYearModel =
					new SpinnerListModel(years);
				spnYear = new JSpinner();
				this.add(spnYear);
				spnYear.setModel(spnYearModel);
				spnYear.setBounds(161, 199, 76, 20);
				spnYear.setInheritsPopupMenu(true);
				spnYear.setValue(years[years.length-1]);
			}
			{
				lblError = new JLabel();
				this.add(lblError);
				lblError.setBounds(147, 11, 277, 21);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void cancelBtnActionPerformed(ActionEvent evt) {
		ToGuiFacade.getInstance().back();
		//ToGuiFacade.getInstance().showUserScreen(_user, true);
	}

	private String copyImage(String path ,String name){
		File fromFile = new File(path);
		File toFile = new File("src/documentation/moviePictures/",name+".jpg"/*fromFile.getName()*/);
		try {
			//System.out.println(toFile.getAbsolutePath());
			toFile.createNewFile();
			toFile.setExecutable(true);
			toFile.setReadable(true);
			toFile.setWritable(true);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		FileInputStream from = null;
	    FileOutputStream to = null;
	    try {
	      from = new FileInputStream(fromFile);
	      to = new FileOutputStream(toFile);
	      byte[] buffer = new byte[4096];
	      int bytesRead;

	      while ((bytesRead = from.read(buffer)) != -1)
	        to.write(buffer, 0, bytesRead); // write
	    } catch (FileNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (IOException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		} finally {
	      if (from != null)
	        try {
	          from.close();
	        } catch (IOException e1) {
	          ;
	        }
	      if (to != null)
	        try {
	          to.close();
	        } catch (IOException e2) {
	          ;
	        }
	    }
		return "documentation/moviePictures/"+toFile.getName();//fromFile.getName();
	}
	public boolean validateEnteredData(){
		String name = txtName.getText();
		String category = txtCategory.getText();
		String director = txtDirector.getText();
		String language = txtLang.getText();
		String length = txtLength.getText();
		String year = (String)spnYear.getValue();
		String picture = txtPicture.getText();
		if ("".equals(name) || "".equals(category) || "".equals(director) || "".equals(language) || "".equals(length) || "".equals(year) || "".equals(picture)){
			lblError.setText("All fields are mandatory");
			return false;
		}
		try{
			Integer.parseInt(length);
		}catch(NumberFormatException e){
			lblError.setText("Length must be an integer");
			return false;
		}
		return true;
	}
}
